package org.september.pisces.region.controller;

import java.text.DecimalFormat;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.september.core.constant.enums.DeleteFlag;
import org.september.core.exception.BusinessException;
import org.september.pisces.region.entity.CurrentRegion;
import org.september.pisces.region.entity.Region;
import org.september.pisces.region.service.RegionService;
import org.september.pisces.user.permission.service.OperationLogService;
import org.september.simpleweb.auth.DefaultMethod;
import org.september.simpleweb.model.ResponseVo;
import org.september.smartdao.CommonDao;
import org.september.smartdao.CommonValidator;
import org.september.smartdao.model.Page;
import org.september.smartdao.model.ParamMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import jakarta.validation.Valid;

@Controller
public class RegionController {

    @Autowired
    private RegionService regionService;
    
    @Autowired
	private CommonDao dao;

    @Autowired
    private CommonValidator commonValidator;
    
    @Autowired
	private OperationLogService operationLogService;

    private static volatile boolean Initiating=false;

    @RequestMapping(RegionTree_Page)
    public ModelAndView regionTree() throws Exception {
        ModelAndView mv = new ModelAndView();
        Region vo = new Region();
        vo.setDeleteFlag(DeleteFlag.NotDelete.ordinal());
        List<Region> list = dao.listByExample(vo);
        if (list.isEmpty()) {
            Region root = new Region();
            root.setName("区域信息");
            root.setParentId(-1L);
            root.setType(0);
            dao.save(root);
            list.add(root);
        }
        mv.addObject("regionList", list);
        return mv;
    }
    
    @ResponseBody
    @PostMapping(RegionTree_Data)
    public ResponseVo<List<Region>> getData(Integer enableFlag) {
    	Region vo = new Region();
        vo.setDeleteFlag(DeleteFlag.NotDelete.ordinal());
        if(enableFlag!=null && enableFlag==1) {
        	vo.setEnableFlag(enableFlag);
        }
        List<Region> list = dao.listByExample(vo);
        return ResponseVo.<List<Region>>BUILDER().setData(list).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @ResponseBody
    @PostMapping(Set_Main_Action)
    public ResponseVo<String> setMainRegion(Long regionId) {
        Region region = dao.get(Region.class, regionId);
        Long zipCode = region.getZipCode();
        CurrentRegion cr = dao.getByExample(new CurrentRegion());
        CurrentRegion currentRegion = new CurrentRegion();
        //zipcode不足6位要前面补0
        DecimalFormat g1 = new DecimalFormat("000000");
        if (zipCode == null) {
            throw new BusinessException("该区域不可设为主区域");
        }
        currentRegion.setFtlName(g1.format(zipCode));
        currentRegion.setRegionId(regionId);
        currentRegion.setZipCode(zipCode);
        currentRegion.setStartFlag(1);
        if (cr == null) {
        	dao.save(currentRegion);
        } else {
            currentRegion.setId(cr.getId());
            dao.update(currentRegion);
        }
//        if (region.getType() == 2) {
//            ParamMap param = new ParamMap();
//            param.put("parentRegionId", region.getId());
//            List<Region> regionList = dao.listByParams(Region.class, "Region.list", param);
//            List<Long> regionIds = regionList.stream().map(Region::getId).collect(Collectors.toList());
//        } else {
//        }
        RegionService.activeRegion= region;
        operationLogService.addLog("设置了为【" + region.getName() + "】主区域");

        return ResponseVo.<String>BUILDER().setData(region.getId().toString()).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @ResponseBody
    @PostMapping(Add_Action)
    public ResponseVo<String> doAddRegion(@Valid Region region) {
        if (commonValidator.exsits(Region.class, new String[]{"name", "parentId", "deleteFlag"}, new Object[]{region.getName(), region.getParentId(), DeleteFlag.NotDelete.ordinal()})) {
            throw new BusinessException("该区域已存在，创建失败！");
        }
        Region parent = dao.get(Region.class, region.getParentId());
        region.setEnableFlag(parent.getEnableFlag());
        dao.save(region);
        operationLogService.addLog("添加了区域【" + region.getName() + "】");
        return ResponseVo.<String>BUILDER().setData(region.getId().toString()).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @ResponseBody
    @PostMapping(Update_Action)
    public ResponseVo<String> doUpdateRegion(@Valid Region region) {
        if (commonValidator.exsitsNotMe(Region.class, new String[]{"name", "parentId", "deleteFlag"}, new Object[]{region.getName(), region.getParentId(), DeleteFlag.NotDelete.ordinal()}, region.getId())) {
            throw new BusinessException("该部门已存在，请修改后再重试！");
        }
        dao.update(region);
//        operationLogService.addLog("修改了区域【" + region.getName() + "】主的信息");
        return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @DefaultMethod
    @ResponseBody
    @PostMapping(GetFlag_Action)
    public ResponseVo<Integer> getFlag(Region region) {
        Region region1 = dao.get(Region.class, region.getId());
        return ResponseVo.<Integer>BUILDER().setData(region1.getEnableFlag()).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @ResponseBody
    @PostMapping(Enbale_Action)
    public ResponseVo<String> doUpdateEnableFlag(Region region) {
        Region region1 = dao.get(Region.class, region.getId());
        regionService.setRegionEnable(region1, region.getEnableFlag());
//        if (region.getEnableFlag() == 1) {
//            operationLogService.addLog("启用了区域【" + region1.getName() + "】");
//        } else {
//            operationLogService.addLog("关闭了区域【" + region1.getName() + "】");
//        }
        return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @ResponseBody
    @PostMapping(Delete_Action)
    public ResponseVo<String> deleteRegion(Region region) {
        Region exists = dao.get(Region.class, region.getId());
        if (exists != null) {
        	exists.setDeleteFlag(1);
        	dao.update(exists);
        } else {
            throw new BusinessException("区域信息错误，删除失败！");
        }
//        operationLogService.addLog("删除了区域【" + region.getName() + "】");
        return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);

    }

    @RequestMapping(Region_List_Page)
    public ModelAndView regionList() throws Exception {
//    	BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
//        TemplateHashModel staticModels = wrapper.getStaticModels();
    	ModelAndView mv = new ModelAndView();
    	
//    	TemplateHashModel optionValueTypeStatics = (TemplateHashModel) staticModels.get(RegionController.class.getName());
//    	mv.addObject("RegionController", optionValueTypeStatics);
//        mv.addObject("DeleteAction", Delete_Action);
        return mv;
    }
    
	@ResponseBody
	@RequestMapping(Region_List_Data)
	public ResponseVo<Page<Region>> listRegionData(String name, Integer type, Page<Region> page) throws Exception {
		ParamMap pm = new ParamMap();
		pm.put("name", name);
		pm.put("type", type);
		page = dao.findPageByParams(Region.class, page, "Region.list", pm);
		return ResponseVo.<Page<Region>>BUILDER().setData(page).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}
	
	@ResponseBody
	@RequestMapping(Init_Action)
	public ResponseVo<String> doInit() throws Exception {
		ParamMap pm = new ParamMap();
		//全局锁控制
		if(Initiating) {
			return ResponseVo.<String>BUILDER().setData("初始化程序正在进行").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
		}
		Initiating = true;
		dao.execute("Region.clear", pm);
		List<String> lines = IOUtils.readLines(this.getClass().getResourceAsStream("init.sql"),"utf8");
		for(String sql : lines) {
			if(sql.startsWith("INSERT INTO")) {
				pm.put("insertSql", sql);
				dao.execute("Region.insert", pm);
			}
		}
		Initiating = false;
		return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}
	
	private static final String Mapping_Prefix = "/pisces/region";
   	public static final String RegionTree_Page = Mapping_Prefix+"/regionEdit";
   	public static final String RegionTree_Data = Mapping_Prefix+"/getData";
   	
   	public static final String Update_Action = Mapping_Prefix+"/doUpdateRegion";
   	public static final String Add_Action = Mapping_Prefix+"/doAddRegion";
   	public static final String Enbale_Action = Mapping_Prefix+"/doUpdateEnableFlag";
   	public static final String Set_Main_Action = Mapping_Prefix+"/setMainRegion";
   	public static final String GetFlag_Action = Mapping_Prefix+"/getFlag";
   	
   	public static final String Region_List_Page = Mapping_Prefix+"/regionList";
   	public static final String Region_List_Data = Mapping_Prefix+"/listRegionData";
   	
   	public static final String Edit_Page = Mapping_Prefix+"/editSetting";
   	public static final String Delete_Action = Mapping_Prefix+"/delete";
   	
   	public static final String Init_Action = Mapping_Prefix+"/doInit";
}
